package com.guosen.zebra.gateway.service;

import com.guosen.zebra.core.common.ZebraConstants;
import com.guosen.zebra.core.registry.etcd.EtcdRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * 服务注册器
 */
@Component
public class ServiceRegister implements ApplicationListener<WebServerInitializedEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegister.class);

    private static final String SERVICE_NAME = "gateway";

    @Autowired
    private EtcdRegistry etcdRegistry;

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {

        // 将网关注册到注册中心上面去
        int port = event.getWebServer().getPort();
        try {
            LOGGER.info("Begin to register gateway service to etcd.");
            etcdRegistry.register(SERVICE_NAME, ZebraConstants.TYPE_GATEWATY, port);
            LOGGER.info("Finish to register gateway service to etcd.");
        } catch (Exception e) {
            LOGGER.error("Failed to register service of gateway to etcd", e);
        }
    }
}
